<?php
/**
 * 商品订单控制器
 * Created by PhpStorm.
 * Author: 芸众商城 www.yunzshop.com
 * Date: 2024/1/1
 * Time: 上午10:00
 */

namespace App\Http\Controllers\Api\store;

use App\Common\Components\ApiController;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\BaseApiController;

class GoodsOrderController extends BaseApiController
{
    /**
     * 获取商品订单列表
     */
    public function getList(Request $request)
    {
        $param = $request->input('param', []);
        $storeId = $request->input('organid', []);
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 10;
        $orderNo = $param['orderNo'] ?? '';
        $memberId = $param['memberId'] ?? '';
        $memberNickname = $param['memberNickname'] ?? '';
        $goodsId = $param['goodsId'] ?? '';
        $goodsName = $param['goodsName'] ?? '';
        $status = $param['status'] ?? '';
        $paymentMethod = $param['paymentMethod'] ?? '';
        $startTime = $param['startTime'] ?? '';
        $endTime = $param['endTime'] ?? '';

        // 查询订单主表，不JOIN商品表，避免数据重复
        $query = DB::table('ims_hhm_order as o')
            ->leftJoin('ims_mc_members as m', 'o.uid', '=', 'm.uid')
            ->select([
                'o.id',
                'o.order_sn',
                'o.price',
                'o.status',
                DB::raw('o.created_at as create_time'),
                'o.pay_time',
                'o.finish_time',
                'o.cancel_time',
                'o.pay_type_id',
                'o.shop_name',
                'm.nickname as member_nickname',
                'm.realname as member_realname',
                'm.mobile as member_mobile',
                'm.avatar as member_avatar'
            ]);

        if (!$storeId) {
            return $this->errorJson('缺少 storeId 参数');
        }

        $query->where('o.store_id', $storeId);

        // 筛选条件
        if ($orderNo) {
            $query->where('o.order_sn', 'like', '%' . $orderNo . '%');
        }
        if ($memberId) {
            $query->where('o.uid', $memberId);
        }
        if ($memberNickname) {
            $query->where(function($q) use ($memberNickname) {
                $q->where('m.nickname', 'like', '%' . $memberNickname . '%')
                  ->orWhere('m.realname', 'like', '%' . $memberNickname . '%')
                  ->orWhere('m.mobile', 'like', '%' . $memberNickname . '%');
            });
        }
        
        // 商品ID筛选 - 使用子查询
        if ($goodsId) {
            $query->whereIn('o.id', function($subQuery) use ($goodsId) {
                $subQuery->select('order_id')
                    ->from('ims_hhm_order_goods')
                    ->where('goods_id', $goodsId);
            });
        }
        
        // 商品名称筛选 - 使用子查询
        if ($goodsName) {
            $query->whereIn('o.id', function($subQuery) use ($goodsName) {
                $subQuery->select('order_id')
                    ->from('ims_hhm_order_goods')
                    ->where('title', 'like', '%' . $goodsName . '%');
            });
        }
        
        if ($status !== null && $status !== '') {
            if ($status == -2) {
                // 全部订单，不添加状态筛选
            } else {
                $query->where('o.status', $status);
            }
        }
        if ($paymentMethod) {
            $query->where('o.pay_type_id', $paymentMethod);
        }
        if ($startTime) {
            $query->where('o.created_at', '>=', strtotime($startTime));
        }
        if ($endTime) {
            $query->where('o.created_at', '<=', strtotime($endTime));
        }

        // 获取总数
        $total = $query->count();

        // 分页查询
        $orders = $query->orderBy('o.created_at', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get();

        // 处理数据并查询每个订单的商品列表
        $list = [];
        foreach ($orders as $order) {
            // 查询该订单的所有商品
            $goods = DB::table('ims_hhm_order_goods')
                ->select(['id', 'title', 'thumb', 'price', 'total', 'goods_id'])
                ->where('order_id', $order->id)
                ->get();

            $order->create_time = date('Y-m-d H:i:s', $order->create_time);
            $order->pay_time = $order->pay_time ? date('Y-m-d H:i:s', $order->pay_time) : '';
            $order->finish_time = $order->finish_time ? date('Y-m-d H:i:s', $order->finish_time) : '';
            $order->cancel_time = $order->cancel_time ? date('Y-m-d H:i:s', $order->cancel_time) : '';
            
            // 状态文本
            $statusMap = [
                0 => '未支付',
                1 => '待发货',
                2 => '待收货',
                3 => '已完成',
                -1 => '已关闭',
                -2 => '退款中',
                -3 => '已退款'
            ];
            $order->status_text = $statusMap[$order->status] ?? '未知状态';
            
            // 支付方式文本
            $payTypeMap = [
                21 => '茶包',
                22 => '沐浴露',
                133 => '茶包',
                137 => '沐浴露',
                1 => '微信支付',
                2 => '支付宝',
                3 => '余额支付',
                4 => '货到付款',
                5 => '后台支付',
                8 => '现金支付'
            ];
            $order->pay_type_text = $payTypeMap[$order->pay_type_id] ?? '其他';
            
            // 将商品列表添加到订单对象
            $order->goods_list = $goods;
            
            // 为了兼容旧的前端代码，保留第一个商品的信息
            if (count($goods) > 0) {
                $order->goods_title = $goods[0]->title;
                $order->goods_thumb = $goods[0]->thumb;
                $order->goods_price = $goods[0]->price;
                $order->goods_total = $goods[0]->total;
            }
            
            $list[] = $order;
        }

        return $this->successJson('获取订单列表成功', [
            'list' => $list,
            'total' => $total,
            'page' => (int)$page,
            'limit' => (int)$limit,
        ]);
    }

    /**
     * 获取商品订单详情
     */
    public function getDetail(Request $request)
    {
        $orderId = $request->input('param.orderId');
        
        if (!$orderId) {
            return $this->errorJson('订单ID不能为空');
        }

        // 获取订单基本信息
        $order = DB::table('ims_hhm_order as o')
            ->leftJoin('ims_mc_members as m', 'o.uid', '=', 'm.uid')
            ->select([
                'o.id',
                'o.uid',
                'o.order_sn',
                'o.price',
                'o.goods_price',
                'o.goods_total',
                'o.status',
                DB::raw('o.created_at as create_time'),
                'o.pay_time',
                'o.finish_time',
                'o.cancel_time',
                'o.pay_type_id',
                'o.shop_name',
                'o.dispatch_price',
                'o.discount_price',
                'o.order_goods_price',
                'o.deduction_price',
                'o.note',
                'm.nickname as member_nickname',
                'm.realname as member_realname',
                'm.mobile as member_mobile',
                'm.avatar as member_avatar'
            ])
            ->where('o.id', $orderId)
            ->first();

        if (!$order) {
            return $this->errorJson('订单不存在');
        }

        // 获取订单商品信息
        $goods = DB::table('ims_hhm_order_goods')
            ->where('order_id', $orderId)
            ->get();

        // 处理时间格式
        $order->create_time = date('Y-m-d H:i:s', $order->create_time);
        $order->pay_time = $order->pay_time ? date('Y-m-d H:i:s', $order->pay_time) : '';
        $order->finish_time = $order->finish_time ? date('Y-m-d H:i:s', $order->finish_time) : '';
        $order->cancel_time = $order->cancel_time ? date('Y-m-d H:i:s', $order->cancel_time) : '';

        // 状态文本
        $statusMap = [
            0 => '未支付',
            1 => '待发货',
            2 => '待收货',
            3 => '已完成',
            -1 => '已关闭',
            -2 => '退款中',
            -3 => '已退款'
        ];
        $order->status_text = $statusMap[$order->status] ?? '未知状态';

        // 支付方式文本
        $payTypeMap = [
            21 => '茶包',
            22 => '沐浴露',
            133 => '茶包',
            137 => '沐浴露',
            1 => '微信支付',
            2 => '支付宝',
            3 => '余额支付',
            4 => '货到付款',
            5 => '后台支付',
            8 => '现金支付'
        ];
        $order->pay_type_text = $payTypeMap[$order->pay_type_id] ?? '其他';
         // 查询核销员信息
         $verifier = null;
         try {
             // 从核销表查询核销记录（type=2换换猫订单，outbound_id是订单id）
             $verifyRecord = DB::table('ims_hhm_vendor_verifiy')
                 ->where('type', 2)
                 ->where('outbound_id', $orderId)
                 ->select(['user_id', 'vendor_id', 'store_id', 'created_at'])
                 ->first();
             
             if ($verifyRecord && $verifyRecord->user_id) {
                 // 查询核销员信息
                 $verifier = DB::table('ims_mc_members as m')
                     ->leftJoin('ims_yz_member as ym', 'm.uid', '=', 'ym.member_id')
                     ->where('m.uniacid', 1)
                     ->where('m.uid', $verifyRecord->user_id)
                     ->whereNull('ym.deleted_at')
                     ->select([
                         'm.uid',
                         'm.avatar',
                         'm.nickname',
                         'm.realname',
                         'm.mobile',
                         'm.createtime',
                         'm.gender',
                         'm.birthyear',
                         'm.birthmonth',
                         'm.birthday',
                         'm.credit1',
                         'm.credit2'
                     ])
                     ->first();
                 
                 if ($verifier) {
                     // 格式化核销员信息
                     $verifier->verify_time = date('Y-m-d H:i:s', $verifyRecord->created_at);
                     $verifier->createtime_text = date('Y-m-d H:i:s', $verifier->createtime);
                 }
             }
         } catch (\Exception $e) {
             // 查询核销员失败不影响订单详情返回，只记录日志
             \Log::warning('查询核销员信息失败: ' . $e->getMessage());
         }

        return $this->successJson('获取订单详情成功', [
            'order' => $order,
            'goods' => $goods,
            'verifier'=>$verifier
        ]);
    }

    /**
     * 关闭订单
     */
    public function closeOrder(Request $request)
    {
        $orderId = $request->input('param.orderId');
        $reason = $request->input('param.reason', '');

        if (!$orderId) {
            return $this->errorJson('订单ID不能为空');
        }

        $order = DB::table('ims_hhm_order')->where('id', $orderId)->first();
        if (!$order) {
            return $this->errorJson('订单不存在');
        }

        if ($order->status != 0) {
            return $this->errorJson('只能关闭未支付的订单');
        }

        // 更新订单状态
        $result = DB::table('ims_hhm_order')
            ->where('id', $orderId)
            ->update([
                'status' => -1,
                'cancel_time' => time(),
                'close_reason' => $reason,
                'updated_at' => time()
            ]);

        if ($result) {
            return $this->successJson('订单已关闭');
        } else {
            return $this->errorJson('关闭订单失败');
        }
    }

    /**
     * 获取订单状态列表
     */
    public function getStatusList()
    {
        $statusList = [
            ['value' => -2, 'label' => '全部订单'],
            ['value' => 0, 'label' => '待支付'],
            ['value' => 1, 'label' => '待发货'],
            ['value' => 2, 'label' => '待收货'],
            ['value' => 3, 'label' => '已完成'],
            ['value' => -1, 'label' => '已关闭'],
            ['value' => -2, 'label' => '退款中'],
            ['value' => -3, 'label' => '已退款']
        ];

        return $this->successJson('获取状态列表成功', $statusList);
    }

    /**
     * 获取支付方式列表
     */
    public function getPaymentMethods()
    {
        $paymentMethods = [
            ['value' => '', 'label' => '全部支付方式'],
            ['value' => 1, 'label' => '微信支付'],
            ['value' => 2, 'label' => '支付宝'],
            ['value' => 3, 'label' => '余额支付'],
            ['value' => 4, 'label' => '货到付款'],
            ['value' => 5, 'label' => '后台支付'],
            ['value' => 8, 'label' => '现金支付'],
            ['value' => 21, 'label' => '茶包支付'],
            ['value' => 22, 'label' => '沐浴露支付']
        ];

        return $this->successJson('获取支付方式成功', $paymentMethods);
    }
}
